package com.small.utils;

import com.small.ConfigConstant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
 * Properties文件帮助类
 * Created by fangzheng on 2018/1/30.
 */
public final class PropUtils {
    private static final Logger logger = LoggerFactory.getLogger(PropUtils.class);
    private static Properties props;

    static {
        //默认加载small.properties文件
        loadProps(ConfigConstant.CONFIG_FILE);
    }

    private static void loadProps(String fileName) {
        logger.info("开始加载properties文件内容.......");
        props = new Properties();
        InputStream in = null;
        try {
            // 要加载的属性文件
            in = PropUtils.class.getClassLoader().getResourceAsStream(fileName);
            props.load(in);
        } catch (FileNotFoundException e) {
            logger.error(fileName + "文件未找到", e);
        } catch (IOException e) {
            logger.error("出现IOException", e);
        } finally {
            try {
                if (null != in) {
                    in.close();
                }
            } catch (IOException e) {
                logger.error(fileName + "文件流关闭出现异常");
            }
        }
    }

    /**
     * 根据key获取properties中的value
     *
     * @param key
     * @return
     */
    public static String getProperty(final String key) {
        if (null == props) loadProps(ConfigConstant.CONFIG_FILE);
        return props.getProperty(key);
    }

    /**
     * 根据key获取指定properties文件中的value
     *
     * @param propertiesFile
     * @param key
     * @return
     */
    public static String getProperty(final String propertiesFile, final String key) {
        loadProps(propertiesFile);
        return props.getProperty(key);
    }

}
